package com.scorpio.framework.service.impl;

import com.scorpio.appuser.domain.AppUserEntity;
import com.scorpio.appuser.dto.LoginUserDetailsDTO;
import com.scorpio.appuser.enums.UserStatusEnum;
import com.scorpio.appuser.mapper.AppUserMapper;
import com.scorpio.appuser.vo.OauthLoginVo;
import com.scorpio.common.exception.CustomException;
import com.scorpio.common.service.impl.BaseServiceImpl;
import com.scorpio.common.utils.ConvertUtils;
import com.scorpio.common.utils.ServletUtils;
import com.scorpio.common.utils.ip.IpUtils;
import com.scorpio.log.domain.UserLoginLogEntity;
import com.scorpio.log.service.UserLoginLogService;
import com.scorpio.sdk.service.WeiXinService;
import com.scorpio.framework.service.LoginServer;
import com.scorpio.framework.service.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class LoginServerImpl extends BaseServiceImpl<AppUserMapper, AppUserEntity> implements LoginServer {

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserLoginLogService loginLogService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginUserDetailsDTO wxOauthLogin(OauthLoginVo vo) {
        String openId = weiXinService.getWxMiniOpenId(vo.getCode());
        return createTokenByOpenId(vo.getNickName(), vo.getAvatarUrl(), openId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginUserDetailsDTO createTokenByOpenId(String nickName, String avatarUrl, String openId) {
        AppUserEntity entity = baseDao.selectByWxOpenId(openId);
        boolean isNewUser = false;
        if (entity == null) {
            if (entity == null) {
                entity = createUser(openId);
                isNewUser = true;
            }
        }
        entity.setNickName(nickName);
        entity.setAvatar(avatarUrl);
        if (baseDao.updateNickNameAvatar(entity.getId(), nickName, avatarUrl) == 0) {
            throw new CustomException("请求失败");
        }
        return loginOperation(entity, isNewUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginUserDetailsDTO loginOperation(AppUserEntity entity, boolean isNewUser) {
        if (!UserStatusEnum.Normal.getValue().equals(entity.getStatus())) {
            throw new CustomException("账号已被封!");
        }
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        UserLoginLogEntity loginLogEntity = new UserLoginLogEntity();
        loginLogEntity.setUid(entity.getId());
        loginLogEntity.setLoginIp(ip);
        loginLogService.save(loginLogEntity);

        LoginUser loginUser = new LoginUser(entity.getId());
        LoginUserDetailsDTO userDetails = ConvertUtils.sourceToTarget(entity, LoginUserDetailsDTO.class);
        //创建登录token
        String token = tokenService.createToken(loginUser);
        userDetails.setToken(token);
        tokenService.strongBackOperation("" + entity.getId(), token);
        return userDetails;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppUserEntity createUser(String openId) {
        AppUserEntity entity = new AppUserEntity();
        entity.setWxOpenId(openId);
        entity.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
        if (baseDao.insert(entity) > 0) {
            return entity;
        }
        throw new CustomException("请稍候再试");
    }
}
